<?php

namespace PKApp\Template;

use PKApp\Template\Classes\ServiceTplParams;
use PKCommon\Controller\AdminController;
use PKFrame\DataHandler\Arrays;

class AdminParams extends AdminController
{

    public function Main()
    {
        $this->callOfSellFunc();
        $this->fetch('tpl_params');
    }

    protected function getParamsList()
    {
        $list = $this->_getList();
        fileHelper()->PutContents(PATH_CACHE . 'Data',
            'tpl_params.php', Arrays::ToSaveString($list));
        $this->json($list);
    }

    private function _getList()
    {
        return $this->_serviceOfTPL()->GetList();
    }

    protected function ApiByChange()
    {
        $post = request()->post();
        $id_post = $this->postId('id','Empty_paramsId');
        $this->_serviceOfTPL()->UpdateById($id_post,['value'=>$post['value']]);
        $this->inputSuccess();
    }
    
    protected function ApiByCreate()
    {
        $post = request()->post();
        $sql = [
            'name' => trim($post['name']),
            'remark'=>trim($post['remark'])
        ];
        if (empty($sql['name']) || empty($sql['remark'])) {
            $this->noticeByJson('tpl_param_empty');
        }
        $where = ['name' => $sql['name']];
        $row = $this->_serviceOfTPL()->GetEntity($where);
        empty($row) ?: $this->noticeByJson('Exists_tplParams');
        $this->_serviceOfTPL()->Add($sql);
        $this->inputSuccess();
    }

    protected function ApiByDel()
    {
        $id_post = $this->postId('id','Empty_paramsId');
        $this->_serviceOfTPL()->DeleteById($id_post);
        $this->inputSuccess();
    }

    private function _serviceOfTPL(): ServiceTplParams
    {
        static $cls;
        !empty($cls) ?: $cls = new ServiceTplParams();
        return $cls;
    }
}